<template>
  <div class="title">
    <label>
<input placeholder="请输入标题"  v-model="title">
    </label>
  </div>
  <div class="Set_tag">
    <span style="position: relative; top:5px; margin-right: 3px" >请选择标签:</span>
    <el-select
      v-model="tag_value"
      multiple
      filterable
      allow-create
      default-first-option
      :reserve-keyword="false"
      placeholder="请选择或者输入标签"
      style="width: 240px"
    >
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.label"
      />
    </el-select>
  </div>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden;"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
  <button @click="getEditorContent" style="margin-top: 10px;">
    获取编辑器内容
  </button>
  <button @click="savePost" style="margin-top: 10px;">
    保存内容
  </button>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { ref, shallowRef, onBeforeUnmount, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import axios from 'axios'
import { API_BASE_URL } from '@/config/config'
import { ElMessage } from 'element-plus'
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const title = ref('')
// 内容 HTML
const valueHtml = ref('')
//标签的内容
const tag_value = ref([])
// 工具栏配置
const toolbarConfig = {}
//标签选项
const options = ref([])
// 编辑器配置
/*const editorConfig = { placeholder: '请输入内容...' }*/
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      // 自定义上传逻辑
      customUpload(file, insertFn) {
        // console.log('上传的文件:', file)

        // 创建 FormData 对象
        const formData = new FormData()
        formData.append('file', file) // 将文件添加到 FormData
        const POST_IMAGE_URL = `${API_BASE_URL}/api/upload-image`
        // 调用后端接口上传文件
        axios.post(POST_IMAGE_URL, formData, {
          headers: {
            'Content-Type': 'multipart/form-data' // 设置请求头
          }, withCredentials: true
        })
          .then((response) => {
            if (response.data.code === 200) {
              const fileUrl = response.data.url // 获取文件访问 URL
              insertFn(fileUrl, file.name) // 将图片 URL 插入到编辑器中
            } else {
              console.error('文件上传失败:', response.data.message)
            }
          })
          .catch((error) => {
            console.error('请求失败:', error)
          })
      }
    }
  }
}
// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
//获取所有帖子分类
const getTagName =async()=> {
  const GET_TAP_URL = `${API_BASE_URL}/tags/all`
  try {
    const response = await axios.get(GET_TAP_URL, {})
    if (response.data.code === 200) {
      ElMessage.success("查询标签分类成功")
      // 将标签数据映射到 options
      options.value = response.data.data.map(tag => ({
        label: tag.name,
        value: tag.id
      }));
    }
  } catch (error) {
    ElMessage.error("查询失败" + error.message)
  }
}
// 编辑器创建时的回调
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
// 获取编辑器内容
const getEditorContent = () => {
  if (editorRef.value) {
    valueHtml.value = editorRef.value.getHtml() // 获取 HTML 内容
    // valueHtml.value = editorRef.value.getText() // 获取纯文本内容
    // console.log(valueHtml)
  } else {
    console.warn('编辑器实例未初始化')
  }
}
//保存帖子的接口
const savePost = async () => {

  const SAVE_URL = `${API_BASE_URL}/posts/save`
  try {
    //获取帖子内容
    const content = editorRef.value.getHtml(); // 使用 getHtml() 方法
    const response = await axios.post(SAVE_URL, null, {
        params: {
          title: title.value,
          content:content,
          tagNames:Array.isArray(tag_value.value)?tag_value.value.join(','):'',
        },withCredentials:true
      }
    )
    if(response.data.code === 200){
      ElMessage.success("帖子保存成功！")
      clearContent()
    }
  } catch
    (error) {
    ElMessage.error('帖子保存失败！' + error.message)
  }
}
onMounted(()=>{
  getTagName();
})
// 清空所有内容
const clearContent = () => {
  title.value = ''; // 清空标题
  tag_value.value = []; // 清空标签
  if (editorRef.value) {
    editorRef.value.clear(); // 清空编辑器内容
  }
};
</script>
<style scoped>

.title {
  width: 100%;
  height: 50px;
  display: block;
  margin-bottom: 10px;
}

.title input {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: larger;
  font-family: "SimHei", "黑体", sans-serif;
  font-weight: bold;
}

.title label {
  display: block;
  width: 100%;
  height: 100%;
}
.Set_tag{
  display: flex;
  margin-bottom: 10px;
}
</style>

